﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Honestysoft.Baseframework.WebUI;
using Honestysoft.Financing.Model;
using System.Data.Common;
using Honestysoft.BaseLibrary.ExceptionHandling;
using Honestysoft.BaseObject;
using System.Configuration;
using System.Data;

namespace Honestysoft.Financing.WebUI.Module.Project
{
    public partial class Project_Edit : BasePage
    {
        protected override void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);
            if (!IsPostBack)
            {
                BindControl();
                Bind();
                //BindAddZBJ();
                BindBudget();
                BindGKLoan();
                BindPlanYear();
                BindProjLoan();
                BindZBJChange();
                BindDOwner();
                BindAT();
            }
        }
        /// <summary>
        /// 当前新增或编辑的项目
        /// </summary>
        private BD_Project obj
        {
            get
            {
                object obj = ViewState["theProject"];
                return obj == null ? null : obj as BD_Project;
            }
            set
            {
                ViewState["theProject"] = value;
            }
        }

        private void BindControl()
        {
            ControlHelper.BindEnum(ddlConType, typeof(EnumItem.ConType));//此处最好改成typeof(EnumItem.XXX)
            ControlHelper.BindEnum(ddlProjectPhase, typeof(EnumItem.ProjectPhase));//此处最好改成typeof(EnumItem.XXX)
            ControlHelper.BindEnum(ddlInvestmentType, typeof(EnumItem.InvestmentType));//此处最好改成typeof(EnumItem.XXX)

            //ddlTableType.Items.Add(new ListItem("A表", "A"));
            //ddlTableType.Items.Add(new ListItem("B表", "B"));
            //ddlTableType.Items.Add(new ListItem("C表", "C"));
            //btnAddBudget.Attributes.Add("onclick", "return addBudget();");
            //btnAddPlanYear.Attributes.Add("onclick", "return addYearPlan();");
            //btnAddProjLoan.Attributes.Add("onclick", "return addProjLoan();");
            //btnAddGKLoan.Attributes.Add("onclick", "return addGKLoan();");
            //btnAddAddZBJ.Attributes.Add("onclick", "return addZBJ();");
        }

        private void Bind()
        {
            if (Request.QueryString["IsToDatabase"] == "1")//属于从收文回执里面进行项目入库的
            {
                //传入的ID是回执的ID
                Bu_DocReceive_Temp docRec = new BaseBusinessLogic<Bu_DocReceive_Temp>(Globals.CurrentConnStringName).GetEntity(Request.QueryString["ID"]);
                Honestysoft.Financing.BusinessLogic.Project bll = new BusinessLogic.Project(Globals.CurrentConnStringName);
                obj = new BD_Project();//肯定是新项目，但要自动入库
                //是否有已存在的同项目代码的项目，有则表示是拆分项目
                BD_Project existsProject = bll.GetDymSplitProjectByCode(docRec.ProjectCode);
                obj.ID = Honestysoft.BaseLibrary.Common.Guid.GetGuid();
                obj.SN = "";
                if (existsProject != null)//存在拆分项目
                {
                    //拆分项目的财政累计安排投资、投资计划、项目贷款额度是相同的
                    obj.YearPlans = existsProject.YearPlans;
                    if (obj.YearPlans != null && obj.YearPlans.Count > 0)
                    {
                        foreach (BD_ProjectInvestmentPlan item in obj.YearPlans)
                        {
                            item.ID = Honestysoft.BaseLibrary.Common.Guid.GetGuid();
                            item.ProjectID = obj.ID;
                        }
                    }
                    obj.LoanAmounts = existsProject.LoanAmounts;
                    if (obj.LoanAmounts != null && obj.LoanAmounts.Count > 0)
                    {
                        foreach (BD_ProjectLoanAmount item in obj.LoanAmounts)
                        {
                            item.ID = Honestysoft.BaseLibrary.Common.Guid.GetGuid();
                            item.ProjectID = obj.ID;
                        }
                    }
                    obj.Owner971 = existsProject.Owner971;
                    obj.IsDymSplit = existsProject.IsDymSplit;
                    obj.IsSplit = existsProject.IsSplit;
                    obj.Owner971Name = existsProject.Owner971Name;
                    obj.FinInvestment = existsProject.FinInvestment;
                    obj.ProjectCategory = existsProject.ProjectCategory;
                    obj.SortCode = existsProject.SortCode;
                    if (existsProject.IsSplit)//如果是拆分项目，自动给予编号
                    {
                        try
                        {
                            int maxSN = Convert.ToInt32(existsProject.SN.Substring(existsProject.SN.IndexOf("(") + 1, existsProject.SN.IndexOf(")") - existsProject.SN.IndexOf("(") - 1));
                            maxSN++;
                            obj.SN = existsProject.SN.Substring(0, existsProject.SN.IndexOf("(") + 1) + maxSN.ToString() + ")";
                        }
                        catch
                        {
                            obj.SN = "";
                        }
                    }
                }
                obj.IsInit = true;
                obj.ConfirmOpinion = "";
                obj.ConfirmTime = DateTime.Now;
                obj.ConfirmUser = UserLoginer.LoginUser.ID;
                obj.Name = docRec.ProjectName;
                obj.Code = docRec.ProjectCode;
                obj.OwnerName = docRec.OwnerName;
                //查找该单位，如果没有，则赋值为名称，保存时自动新增
                QueryParameters query = new QueryParameters();
                query.Add("CompName", docRec.OwnerName, QueryParameters.OperatorType.Equal);
                List<Honestysoft.Baseframework.Model.Org_Company> lsComp = new BaseBusinessLogic<Honestysoft.Baseframework.Model.Org_Company>(Globals.CurrentConnStringName).GetEntitys(query);
                if (lsComp != null && lsComp.Count == 1)
                {
                    hidOwner.Value = lsComp[0].ID;
                }
                else
                {
                    hidOwner.Value = docRec.OwnerName;
                }
                txtName.Text = obj.Name;
                txtCode.Text = obj.Code;
                txtOwner.Text = obj.OwnerName;
                txtName.Enabled = false;
                txtCode.Enabled = false;
                chkIsDymSplit.Checked = obj.IsDymSplit;
                chkIsSplit.Checked = obj.IsSplit;
                hidOwner971.Value = obj.Owner971;
                txtOwner971.Text = obj.Owner971Name;
                
                numFinInvestment.Text = obj.FinInvestment.ToString("0.00");
                txtSN.Text = obj.SN;
            }
            else
            {
                if (!string.IsNullOrEmpty(Request.QueryString["ID"]))
                {
                    obj = new Honestysoft.Financing.BusinessLogic.Project(Globals.CurrentConnStringName).GetFullProject(Request.QueryString["ID"]);
                    txtCode.Text = obj.Code;
                    txtSN.Text = obj.SN;
                    txtName.Text = obj.Name;
                    txtOfficialNo.Text = obj.OfficialNo;
                    chkIsSplit.Checked = obj.IsSplit;
                    chkIsDymSplit.Checked = obj.IsDymSplit;
                    hidOwner971.Value = obj.Owner971;
                    hidOwner.Value = obj.Owner;
                    txtOwner971.Text = obj.Owner971Name;
                    txtOwner.Text = obj.OwnerName;
                    hidDOwner.Value = obj.DOwner;
                    txtDOwner.Text = obj.DOwnerName;
                    hidFCode.Value = obj.FCode;
                    ddlConType.SelectedValue = obj.ConType;
                    dtpPlanStart.Text = (obj.PlanStart.HasValue ? obj.PlanStart.Value.ToString("yyyy-MM-dd") : "");
                    dtpPlanEnd.Text = (obj.PlanEnd.HasValue ? obj.PlanEnd.Value.ToString("yyyy-MM-dd") : "");
                    dtpStartDate.Text = (obj.StartDate.HasValue ? obj.StartDate.Value.ToString("yyyy-MM-dd") : "");
                    dtpEndDate.Text = (obj.EndDate.HasValue ? obj.EndDate.Value.ToString("yyyy-MM-dd") : "");
                    ddlProjectPhase.SelectedValue = obj.ProjectPhase;
                    txtContact.Text = obj.Contact;
                    txtContactPhone.Text = obj.ContactPhone;
                    txtRemark.Text = obj.Remark;
                    //FCKeditor2.Value = obj.Overview;
                    ddlInvestmentType.SelectedValue = obj.InvestmentType;
                    numFinInvestment.Text = obj.FinInvestment.ToString("0.00");
                    numInvestment.Text = obj.Investment.ToString("0.00");
                    numTotalCapitalAmount.Text = obj.TotalCapitalAmount.ToString("0.00");
                    if (obj.IsInit)
                    {
                        //txtCode.Enabled = false;
                        //txtName.Enabled = false;
                        //txtSN.Enabled = false;
                        //btnSelect1.Enabled = false;
                        //btnSelect2.Enabled = false;
                        //numInvestment.Enabled = false;
                        //ddlInvestmentType.Enabled = false;
                        //numFinInvestment.Enabled = false;
                        //numTotalCapitalAmount.Enabled = false;
                        //chkIsSplit.Enabled = false;
                        //chkIsDymSplit.Enabled = false;
                    }
                }
                else
                {
                    obj = new BD_Project();
                    obj.ID = Honestysoft.BaseLibrary.Common.Guid.GetGuid();
                    obj.IsInit = false;
                    //numSortCode.Text = obj.SortCode.ToString();
                    //hidCurTCAmountDate.Value = DateTime.Now.ToString("yyyy-MM-dd");
                }
            }
        }

        private void BindAT()
        {
            if (Request.QueryString["IsToDatabase"] != "1" && !string.IsNullOrEmpty(Request.QueryString["ID"]))
            {
                QueryParameters query = new QueryParameters();
                query.Add("ProjectID", Request.QueryString["ID"], QueryParameters.OperatorType.Equal);
                OrderParameters order = new OrderParameters();
                order.Add("Code");
                DataTable dtAT = new BaseBusinessLogic<Bu_AuditTable>().GetTable(query, order);
                DataTable dtContract = new BaseBusinessLogic<BD_Contract>().GetTable(query, order);
                DataTable dt = new DataTable();
                dt.Columns.Add("ContractID", typeof(string));
                dt.Columns.Add("Code", typeof(string));
                dt.Columns.Add("FirstDate", typeof(DateTime));
                dt.Columns.Add("Amount_S", typeof(decimal));
                dt.Columns.Add("GiveDate", typeof(DateTime));
                dt.Columns.Add("GiveAmount", typeof(decimal));
                dt.Columns.Add("BFDate", typeof(DateTime));
                dt.Columns.Add("BFAmount", typeof(decimal));
                DataRow drNew = null;
                foreach (DataRow dr in dtContract.Rows)
                {
                    drNew = dt.NewRow();
                    drNew["ContractID"] = dr["ID"].ToString();
                    drNew["Code"] = dr["Code"].ToString();
                    if (dtAT != null && dtAT.Rows.Count > 0)
                    {
                        drNew["FirstDate"] = dtAT.Compute("Max(FirstDate)", "ContractID='" + dr["ID"].ToString() + "'");
                        drNew["Amount_S"] = dtAT.Compute("Sum(Amount_S)", "ContractID='" + dr["ID"].ToString() + "'");
                        drNew["GiveDate"] = dtAT.Compute("Max(GiveDate)", "ContractID='" + dr["ID"].ToString() + "'");
                        drNew["GiveAmount"] = dtAT.Compute("Sum(GiveAmount)", "ContractID='" + dr["ID"].ToString() + "'");
                        drNew["BFDate"] = dtAT.Compute("Max(BFDate)", "ContractID='" + dr["ID"].ToString() + "'");
                        drNew["BFAmount"] = dtAT.Compute("Sum(BFAmount)", "ContractID='" + dr["ID"].ToString() + "'");
                    }
                    dt.Rows.Add(drNew);
                }
                repATList.DataSource = dt;
                repATList.DataBind();
                decimal totalAmount_S = 0; 
                decimal totalGiveAmount = 0;
                decimal totalBFAmount = 0;
                decimal loanAmount =new Honestysoft.Financing.BusinessLogic.Project("").GetProjectLoanAmount(Request.QueryString["ID"], DateTime.Today.Year);
                if (dtAT != null && dtAT.Rows.Count > 0)
                {
                    totalAmount_S = Convert.ToDecimal(dtAT.Compute("Sum(Amount_S)", "ProjectID='" + Request.QueryString["ID"] + "'"));
                    totalGiveAmount = Convert.ToDecimal(dtAT.Compute("Sum(GiveAmount)", "ProjectID='" + Request.QueryString["ID"] + "'"));
                    totalBFAmount = Convert.ToDecimal(dtAT.Compute("Sum(BFAmount)", "ProjectID='" + Request.QueryString["ID"] + "'"));
                }
                lblAmount_S.Text = string.Format("{0:N}", totalAmount_S);
                lblGiveAmount.Text = string.Format("{0:N}", totalGiveAmount);
                lblBFAmount.Text = string.Format("{0:N}", totalBFAmount);
                lblPP_Amount_S.Text = (loanAmount == 0 ? "" : string.Format("{0:P}", totalAmount_S / loanAmount));
                lblPP_GiveAmount.Text = (loanAmount == 0 ? "" : string.Format("{0:P}", totalGiveAmount / loanAmount));
                lblPP_BFAmount.Text = (loanAmount == 0 ? "" : string.Format("{0:P}", totalBFAmount / loanAmount));
            }
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            Honestysoft.Financing.BusinessLogic.Project bll = new BusinessLogic.Project(Globals.CurrentConnStringName);
            DbTransaction transaction = Honestysoft.BaseLibrary.Data.DatabaseProvider.GetDbTransaction(Globals.CurrentConnStringName);
            DbConnection connection = transaction.Connection;
            string maxCode = "";
            Honestysoft.Financing.BusinessLogic.Reports rptBll = new BusinessLogic.Reports(Globals.CurrentConnStringName);
                    
            if (Request.QueryString["IsToDatabase"] == "1")//属于从收文回执里面进行项目入库的
            {                
                try
                {
                    if (hidOwner.Value == txtOwner.Text)//需要新增单位
                    {
                        Honestysoft.Baseframework.Model.Org_Company newCompany = new Honestysoft.Baseframework.Model.Org_Company();
                        newCompany.CategoryID = ConfigurationManager.AppSettings["CompanyCategory_JS"];
                        maxCode = rptBll.GetMaxCompanyCode();
                        newCompany.CompCode = "GS-" + (Convert.ToInt32(maxCode.Substring(3)) + 1).ToString().PadLeft(4, '0');
                        maxCode = newCompany.CompCode;
                        newCompany.CompName = txtOwner.Text;
                        newCompany.ID = Honestysoft.BaseLibrary.Common.Guid.GetGuid();
                        newCompany.IsInner = false;
                        newCompany.IsValid = true;
                        newCompany.SortCode = Convert.ToInt32(maxCode.Substring(3)) + 1;
                        new BaseBusinessLogic<Honestysoft.Baseframework.Model.Org_Company>(Globals.CurrentConnStringName).CreateEntity(newCompany, transaction);
                        hidOwner.Value = newCompany.ID;
                    }
                    //如果有委托代建单位
                    if (txtDOwner.Text.Trim().Length > 0)
                    {
                        string id = rptBll.GetCompanyIdByName(txtDOwner.Text.Trim(), transaction);
                        if (id == "")
                        {
                            Honestysoft.Baseframework.Model.Org_Company newCompany = new Honestysoft.Baseframework.Model.Org_Company();
                            newCompany.CategoryID = ConfigurationManager.AppSettings["CompanyCategory_JS"];
                            if (maxCode == "")
                            {
                                maxCode = rptBll.GetMaxCompanyCode();
                            }
                            newCompany.CompCode = "GS-" + (Convert.ToInt32(maxCode.Substring(3)) + 1).ToString().PadLeft(4, '0');
                            newCompany.CompName = txtDOwner.Text.Trim();
                            newCompany.ID = Honestysoft.BaseLibrary.Common.Guid.GetGuid();
                            newCompany.IsInner = false;
                            newCompany.IsValid = true;
                            newCompany.SortCode = Convert.ToInt32(maxCode.Substring(3)) + 1;
                            new BaseBusinessLogic<Honestysoft.Baseframework.Model.Org_Company>(Globals.CurrentConnStringName).CreateEntity(newCompany, transaction);
                            hidDOwner.Value = newCompany.ID;
                        }
                        else
                        {
                            hidDOwner.Value = id;
                        }
                    }
                    SetSubmitObject();
                    bll.ProjectToDatabase(obj, Request.QueryString["ID"], transaction);
                    transaction.Commit();
                    ScriptHelper.Window.AlertClose("项目入库成功，请进行合同入库！", true);
                }
                catch (BaseException bex)
                {
                    transaction.Rollback();
                    ExceptionHelper.ExceptionDistribute(bex, false);
                    ScriptHelper.Window.Alert(bex.Message);
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    ExceptionHelper.ExceptionDistribute(ex, false);
                    ScriptHelper.Window.Alert("保存失败！系统发生了未知错误！");
                }
                finally
                {
                    connection.Close();
                }
            }
            else
            {
                try
                {
                    //如果有委托代建单位
                    if (txtDOwner.Text.Trim().Length > 0)
                    {
                        string id = rptBll.GetCompanyIdByName(txtDOwner.Text.Trim(), transaction);
                        if (id == "")
                        {
                            Honestysoft.Baseframework.Model.Org_Company newCompany = new Honestysoft.Baseframework.Model.Org_Company();
                            newCompany.CategoryID = ConfigurationManager.AppSettings["CompanyCategory_JS"];
                            if (maxCode == "")
                            {
                                maxCode = rptBll.GetMaxCompanyCode();
                            }
                            newCompany.CompCode = "GS-" + (Convert.ToInt32(maxCode.Substring(3)) + 1).ToString().PadLeft(4, '0');
                            newCompany.CompName = txtDOwner.Text.Trim();
                            newCompany.ID = Honestysoft.BaseLibrary.Common.Guid.GetGuid();
                            newCompany.IsInner = false;
                            newCompany.IsValid = true;
                            newCompany.SortCode = Convert.ToInt32(maxCode.Substring(3)) + 1;
                            new BaseBusinessLogic<Honestysoft.Baseframework.Model.Org_Company>(Globals.CurrentConnStringName).CreateEntity(newCompany, transaction);
                            hidDOwner.Value = newCompany.ID;
                        }
                        else
                        {
                            hidDOwner.Value = id;
                        }
                    }
                    SetSubmitObject();
                    bll.SaveProject(obj, transaction);
                    if (hidFCode.Value != obj.FCode)//修改了项目编号，合同编号必须更新，未完成的作业表的编号也要更新
                    { 

                    }
                    transaction.Commit();
                    ScriptHelper.Window.AlertClose("保存成功！", true);
                }
                catch (BaseException bex)
                {
                    transaction.Rollback();
                    ExceptionHelper.ExceptionDistribute(bex, false);
                    ScriptHelper.Window.Alert(bex.Message);
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    ExceptionHelper.ExceptionDistribute(ex, false);
                    ScriptHelper.Window.Alert("保存失败！系统发生了未知错误！");
                }
                finally
                {
                    connection.Close();
                }
            }
        }

        /// <summary>
        /// 新增
        /// </summary>
        private void Add()
        {
            try
            {
                SetSubmitObject();
                int ret = new BaseBusinessLogic<BD_Project>().CreateEntity(obj);
                if (ret == 1)
                {
                    ScriptHelper.Window.AlertClose("保存成功！", true);
                }
                else
                {
                    ScriptHelper.Window.Alert("保存失败！");
                }
            }
            catch (BaseException bex)
            {
                ExceptionHelper.ExceptionDistribute(bex, false);
                ScriptHelper.Window.Alert(bex.Message);
            }
            catch (Exception ex)
            {
                ExceptionHelper.ExceptionDistribute(ex, false);
                ScriptHelper.Window.Alert("保存失败！系统发生了未知错误！");
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        private void Edit()
        {
            try
            {
                SetSubmitObject();
                int ret = new BaseBusinessLogic<BD_Project>().UpdateEntity(obj);
                if (ret == 1)
                {
                    ScriptHelper.Window.AlertClose("保存成功！", true);
                }
                else
                {
                    ScriptHelper.Window.Alert("保存失败！");
                }
            }
            catch (BaseException bex)
            {
                ExceptionHelper.ExceptionDistribute(bex, false);
                ScriptHelper.Window.Alert(bex.Message);
            }
            catch (Exception ex)
            {
                ExceptionHelper.ExceptionDistribute(ex, false);
                ScriptHelper.Window.Alert("保存失败！系统发生了未知错误！");
            }
        }
        /// <summary>
        /// 得到提交对象
        /// </summary>
        /// <returns></returns>
        private void SetSubmitObject()
        {
            if (Request.QueryString["IsToDatabase"] == "1")//属于从收文回执里面进行项目入库的
            {
                obj.dataState = EnumItem.DataState.New;
            }
            else
            {
                if (!string.IsNullOrEmpty(Request.QueryString["ID"]))
                {
                    obj.dataState = EnumItem.DataState.Modify;
                    decimal nowZBJ = 0;
                    if (numTotalCapitalAmount.Text.Trim().Length > 0)
                    {
                        nowZBJ = Convert.ToDecimal(numTotalCapitalAmount.Text);
                    }
                    if (obj.TotalCapitalAmount != nowZBJ)//如果修改了资本金
                    {
                        BD_ProjectZBJChange zbjchange = new BD_ProjectZBJChange();
                        zbjchange.ChangeZBJ = nowZBJ;
                        zbjchange.CreateTime=DateTime.Now;
                        zbjchange.Creator=UserLoginer.LoginUser.ID;
                        zbjchange.CreatorName=UserLoginer.LoginUser.Name;
                        zbjchange.dataState = EnumItem.DataState.New;
                        zbjchange.ID = Honestysoft.BaseLibrary.Common.Guid.GetGuid();
                        zbjchange.ProjectID = obj.ID;
                        zbjchange.SourceZBJ = obj.TotalCapitalAmount;
                        zbjchange.UseBatchID="";
                        if (obj.ZBJChanges == null)
                        {
                            obj.ZBJChanges = new List<BD_ProjectZBJChange>();
                        }
                        obj.ZBJChanges.Add(zbjchange);
                    }
                }
                else
                {
                    obj.dataState = EnumItem.DataState.New;
                }
            }
            string sn = txtSN.Text;
            sn = sn.Replace("（", "(").Replace("）", ")");
            if (sn.EndsWith(")"))//有括号
            {
                string lsn = ""; //前半部分
                string rsn = "";
                lsn = sn.Substring(0, sn.IndexOf("("));
                rsn = sn.Substring(sn.IndexOf("("));
                obj.FCode = "F" + lsn.PadLeft(3, '0') + rsn;
            }
            else
            {
                obj.FCode = "F" + sn.PadLeft(3, '0');
            }
            obj.IsDymSplit = chkIsDymSplit.Checked;
            obj.Code = txtCode.Text;
            obj.SN = txtSN.Text;
            obj.ProjectCategory = "";// ddlProjectCategory.SelectedValue;
            obj.Name = txtName.Text;
            obj.OfficialNo = txtOfficialNo.Text;
            obj.IsSplit = chkIsSplit.Checked;
            obj.Owner971 = hidOwner971.Value;
            obj.Owner = hidOwner.Value;
            obj.DOwner = hidDOwner.Value;
            obj.ConType = ddlConType.SelectedValue;
            if (dtpPlanStart.Text.Trim().Length > 0) { obj.PlanStart = Convert.ToDateTime(dtpPlanStart.Text); }
            if (dtpPlanEnd.Text.Trim().Length > 0) { obj.PlanEnd = Convert.ToDateTime(dtpPlanEnd.Text); }
            if (dtpStartDate.Text.Trim().Length > 0) { obj.StartDate = Convert.ToDateTime(dtpStartDate.Text); }
            if (dtpEndDate.Text.Trim().Length > 0) { obj.EndDate = Convert.ToDateTime(dtpEndDate.Text); }
            obj.ProjectPhase = ddlProjectPhase.SelectedValue;
            obj.Contact = txtContact.Text;
            obj.ContactPhone = txtContactPhone.Text;
            obj.Progress = "";// txtProgress.Text;
            obj.Scale = "";//txtScale.Text;
            obj.Content = "";//txtContent.Text;
            obj.Infor = "";//txtInfor.Text;
            //obj.Overview = FCKeditor2.Value;// txtOverview.Text;
            obj.Problems = "";// txtProblems.Text;
            obj.Remark = txtRemark.Text;
            if (numFinInvestment.Text.Trim().Length > 0) { obj.FinInvestment = Convert.ToDecimal(numFinInvestment.Text); }
            if (numInvestment.Text.Trim().Length > 0) { obj.Investment = Convert.ToDecimal(numInvestment.Text); }
            obj.InvestmentType = ddlInvestmentType.SelectedValue;
            if (numTotalCapitalAmount.Text.Trim().Length > 0) { obj.TotalCapitalAmount = Convert.ToDecimal(numTotalCapitalAmount.Text); }

        }

        #region old

        #region 概算

        private void BindBudget()
        {
            rptList_Budget.DataSource = obj.Budgets;
            rptList_Budget.DataBind();
            hidLastBudget.Value = obj.LastBudget.ToString("0.00");
            lblInvestment.Visible = false;
            if (obj.Budgets != null && obj.Budgets.Count > 0)
            {
                numInvestment.Visible = false;
                lblInvestment.Visible = true;
                lblInvestment.Text = "变更前：" + string.Format("{0:N}", obj.BGQBudget)+"<br/>变更后：" + string.Format("{0:N}", obj.LastBudget);
            }
        }
        /// <summary>
        /// 得到表格行操作按钮脚本
        /// </summary>
        /// <param name="dataId">记录ID</param>
        /// <returns>操作按钮脚本</returns>
        //protected string GetButtonScriptBudget(string dataId)
        //{
        //    string script = "";
        //    if (PageSecurity.View)
        //    {
        //        script = ScriptHelper.LinkButton.GetGridViewButton(Globals.Home + "Module/Project/BD_ProjectBudget_View.aspx", "查看项目概算变动", 400, 370, dataId, FunctionID);
        //    }
        //    return script;
        //}

        protected void btnAddBudget_Click(object sender, EventArgs e)
        {
            string json = hidAddBudget.Value;
            hidAddBudget.Value = "";
            BD_ProjectBudget newItem =  JsonHelper.JsonDeserialize<BD_ProjectBudget>(json);
            newItem.SponsorName = Server.UrlDecode(newItem.SponsorName);
            newItem.Reason = Server.UrlDecode(newItem.Reason);
            if (obj.Budgets == null) { obj.Budgets = new List<BD_ProjectBudget>(); }
            obj.Budgets.Insert(0, newItem);            
            BindBudget();            
            Page.ClientScript.RegisterStartupScript(typeof(string), "doTab", "document.getElementById('li1').click();", true);
        }

        #endregion

        #region 投资计划
        private void BindPlanYear()
        {
            rptList_PlanYear.DataSource = obj.YearPlans;
            rptList_PlanYear.DataBind();
        }
        ///// <summary>
        ///// 得到表格行操作按钮脚本
        ///// </summary>
        ///// <param name="dataId">记录ID</param>
        ///// <returns>操作按钮脚本</returns>
        //protected string GetButtonScriptPlanYear(string dataId)
        //{
        //    string script = "";
        //    if (PageSecurity.View)
        //    {
        //        script = ScriptHelper.LinkButton.GetGridViewButton(Globals.Home + "Module/Project/BD_ProjectInvestmentPlan_View.aspx", "查看项目投资计划", 400, 300, dataId, FunctionID);
        //    }
        //    return script;
        //}
        protected void btnAddPlanYear_Click(object sender, EventArgs e)
        {
            string json = hidAddYearPlan.Value;
            hidAddYearPlan.Value = "";
            BD_ProjectInvestmentPlan newItem = JsonHelper.JsonDeserialize<BD_ProjectInvestmentPlan>(json);
            newItem.SponsorName = Server.UrlDecode(newItem.SponsorName);
            newItem.Remark = Server.UrlDecode(newItem.Remark);
            if (obj.YearPlans == null) { obj.YearPlans = new List<BD_ProjectInvestmentPlan>(); }
            obj.YearPlans.Insert(0, newItem);
            BindPlanYear();
            Page.ClientScript.RegisterStartupScript(typeof(string), "doTab", "document.getElementById('li2').click();", true);
        }

        #endregion

        #region 项目贷款额度
        private void BindProjLoan()
        {
            rptList_ProjLoan.DataSource = obj.LoanAmounts;
            rptList_ProjLoan.DataBind();
        }
        ///// <summary>
        ///// 得到表格行操作按钮脚本
        ///// </summary>
        ///// <param name="dataId">记录ID</param>
        ///// <returns>操作按钮脚本</returns>
        //protected string GetButtonScriptProjLoan(string dataId)
        //{
        //    string script = "";
        //    if (PageSecurity.View)
        //    {
        //        script = ScriptHelper.LinkButton.GetGridViewButton(Globals.Home + "Module/Project/BD_ProjectLoanAmount_View.aspx", "查看项目贷款额度", 400, 370, dataId, FunctionID);
        //    }
        //    return script;
        //}
        protected void btnAddProjLoan_Click(object sender, EventArgs e)
        {
            string json = hidAddProjLoan.Value;
            hidAddProjLoan.Value = "";
            BD_ProjectLoanAmount newItem = JsonHelper.JsonDeserialize<BD_ProjectLoanAmount>(json);
            newItem.SponsorName = Server.UrlDecode(newItem.SponsorName);
            newItem.Remark = Server.UrlDecode(newItem.Remark);
            if (obj.LoanAmounts == null) { obj.LoanAmounts = new List<BD_ProjectLoanAmount>(); }
            obj.LoanAmounts.Insert(0, newItem);
            BindProjLoan();
            Page.ClientScript.RegisterStartupScript(typeof(string), "doTab", "document.getElementById('li3').click();", true);
        }
        #endregion

        #region 国开行贷款额度
        private void BindGKLoan()
        {
            rptList_GKLoan.DataSource = obj.GKLoanAmounts;
            rptList_GKLoan.DataBind();
        }
        ///// <summary>
        ///// 得到表格行操作按钮脚本
        ///// </summary>
        ///// <param name="dataId">记录ID</param>
        ///// <returns>操作按钮脚本</returns>
        //protected string GetButtonScriptGKLoan(string dataId)
        //{
        //    string script = "";
        //    if (PageSecurity.View)
        //    {
        //        script = ScriptHelper.LinkButton.GetGridViewButton(Globals.Home + "Module/Project/BD_ProjectGKLoanAmount_View.aspx", "查看项目贷款额度", 400, 370, dataId, FunctionID);
        //    }
        //    return script;
        //}
        protected void btnAddGKLoan_Click(object sender, EventArgs e)
        {
            string json = hidAddGKLoan.Value;
            hidAddGKLoan.Value = "";
            BD_ProjectGKLoanAmount newItem = JsonHelper.JsonDeserialize<BD_ProjectGKLoanAmount>(json);
            newItem.SponsorName = Server.UrlDecode(newItem.SponsorName);
            newItem.Remark = Server.UrlDecode(newItem.Remark);
            if (obj.GKLoanAmounts == null) { obj.GKLoanAmounts = new List<BD_ProjectGKLoanAmount>(); }
            obj.GKLoanAmounts.Insert(0, newItem);
            BindGKLoan();
            Page.ClientScript.RegisterStartupScript(typeof(string), "doTab", "document.getElementById('li4').click();", true);
        }
        #endregion

        #region 新增资本金
        ///// <summary>
        ///// 得到选中的记录ID集合
        ///// </summary>
        ///// <returns></returns>
        //private string[] GetSelectedRowKeys()
        //{
        //    string strId = Request["chkID"] + "";
        //    if (string.IsNullOrEmpty(strId)) { return null; }
        //    return strId.Split(',');
        //}
        //private void BindAddZBJ()
        //{
        //    if (obj.AddInvesments != null &&obj.AddInvesments.Count > 0)
        //    {
        //        rptList_AddZBJ.DataSource = obj.AddInvesments.FindAll((BD_ProjectAddInvestment find) => find.dataState != EnumItem.DataState.Delete);
        //        rptList_AddZBJ.DataBind();
        //    }
        //}
        ///// <summary>
        ///// 得到表格行操作按钮脚本
        ///// </summary>
        ///// <param name="dataId">记录ID</param>
        ///// <returns>操作按钮脚本</returns>
        //protected string GetButtonScriptAddZBJ(string dataId)
        //{
        //    string script = "";
        //    //if (PageSecurity.Edit)
        //    //{
        //    //    script += ScriptHelper.LinkButton.GetGridImageButton("document.getElementById('" + hidEditAddZBJID.ClientID + "').value='" + dataId + "';document.getElementById('" + btnEditAddZBJ.ClientID + "').click();", ScriptHelper.Image.GetUrl(ScriptHelper.Image.ImageType.Edit), "修改新增资本金", "");

        //    //    // script += ScriptHelper.LinkButton.GetGridEditButton(Globals.Home + "Module/Project/BD_ProjectAddInvestment_Edit.aspx", "修改项目新增资本金", 400, 370, dataId, FunctionID);
        //    //}
        //    //if (PageSecurity.Delete)
        //    //{
        //    //    if (script.Length > 0) { script += "&nbsp;"; }
        //        script += ScriptHelper.LinkButton.GetGridDeleteButton(dataId, btnDeleteAddZBJ.ClientID);
        //    //}
        //    //if (PageSecurity.View)
        //    //{
        //    //    if (script.Length > 0) { script += "&nbsp;"; }
        //    //    script += ScriptHelper.LinkButton.GetGridViewButton(Globals.Home + "Module/Project/BD_ProjectAddInvestment_View.aspx", "查看项目新增资本金", 400, 370, dataId, FunctionID);
        //    //}
        //    return script;
        //}
        //protected void btnAddAddZBJ_Click(object sender, EventArgs e)
        //{
        //    string json = hidAddAddZBJ.Value;
        //    hidAddAddZBJ.Value = "";
        //    BD_ProjectAddInvestment newItem = JsonHelper.JsonDeserialize<BD_ProjectAddInvestment>(json);
        //    newItem.SponsorName = Server.UrlDecode(newItem.SponsorName);
        //    newItem.Remark = Server.UrlDecode(newItem.Remark);
        //    if (obj.AddInvesments == null) { obj.AddInvesments = new List<BD_ProjectAddInvestment>(); }
        //    obj.AddInvesments.Insert(0, newItem);
        //    BindAddZBJ();
        //    Page.ClientScript.RegisterStartupScript(typeof(string), "doTab", "document.getElementById('li6').click();", true);
        //}
        ////protected void btnEditAddZBJ_Click(object sender, EventArgs e)
        ////{
        ////    BindAddZBJ();
        ////    Page.ClientScript.RegisterStartupScript(typeof(string), "doTab", "document.getElementById('li6').click();", true);
        ////}
        //protected void btnDeleteAddZBJ_Click(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        string[] arrId = GetSelectedRowKeys();
        //        foreach (BD_ProjectAddInvestment item in obj.AddInvesments)
        //        {
        //            if (arrId.Contains<string>(item.ID))
        //            {
        //                item.dataState = EnumItem.DataState.Delete;
        //            }
        //        }
        //        BindAddZBJ();
        //        Page.ClientScript.RegisterStartupScript(typeof(string), "doTab", "document.getElementById('li6').click();", true);
        //    }
        //    catch (Honestysoft.BaseLibrary.ExceptionHandling.BaseException bex)
        //    {
        //        ExceptionHelper.ExceptionDistribute(bex, false);
        //        ScriptHelper.Window.Alert(bex.Message);
        //    }
        //    catch (Exception ex)
        //    {
        //        ExceptionHelper.ExceptionDistribute(ex, false);
        //        ScriptHelper.Window.Alert("删除失败！系统发生了未知错误！");
        //    }
        //}
        private void BindZBJChange()
        {
            rptZBJChangeList.DataSource = obj.ZBJChanges;
            rptZBJChangeList.DataBind();
        }
        #endregion

        

        #endregion

        private void BindDOwner()
        {
            if (obj.Companys != null)
            {
                List<BD_ProjectCompany> lsDOwner = obj.Companys.FindAll((BD_ProjectCompany find) => find.dataState != EnumItem.DataState.Delete);
                rptDOwnerList.DataSource = lsDOwner;
                rptDOwnerList.DataBind();
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (obj.Companys == null) { obj.Companys = new List<BD_ProjectCompany>(); }
            int maxSortCode = 0;
            foreach(BD_ProjectCompany item in obj.Companys)
            {
                if (item.SortCode > maxSortCode) { maxSortCode = item.SortCode; }
            }
            string[] arrID = hidDOwner.Value.Split(',');
            string[] arrName = txtDOwner.Text.Split(',');
            BD_ProjectCompany newCompany = null;
            for (int i = 0; i < arrID.Length; i++)
            {
                //如果已经有该公司，则不新增
                if (obj.Companys.Exists((BD_ProjectCompany find) => find.CompanyID == arrID[i]))
                {
                    continue;
                }
                newCompany = new BD_ProjectCompany();
                newCompany.CompanyID = arrID[i];
                newCompany.CompanyName = arrName[i];
                newCompany.ID = Honestysoft.BaseLibrary.Common.Guid.GetGuid();
                newCompany.ProjectID = obj.ID;
                newCompany.SortCode = maxSortCode++;
                newCompany.UnitType = ((int)EnumItem.UnitType.DOwner).ToString();
                newCompany.dataState = EnumItem.DataState.New;
                obj.Companys.Add(newCompany);
            }
            hidDOwner.Value = "";
            txtDOwner.Text = "";
            BindDOwner();
        }
        private string[] GetSelectedRowKeys()
        {
            string strId = Request["chkID"] + "";
            if (string.IsNullOrEmpty(strId)) { return null; }
            return strId.Split(',');
        }
        protected void Button2_Click(object sender, EventArgs e)
        {
            if (obj.Companys != null)
            {
                string[] arrDelete = GetSelectedRowKeys();
                foreach (BD_ProjectCompany item in obj.Companys)
                {
                    if (arrDelete.Contains<string>(item.ID))
                    {
                        item.dataState = EnumItem.DataState.Delete;
                    }
                }
                BindDOwner();
            }
        }

    }
}
